//
//  MLGameLayer.m
//  WaterProof
//
//  Created by victor0321 on 12/1/4.
//  Copyright 2012年 __MyCompanyName__. All rights reserved.
//

#import "MLGameLayer.h"
#import "MLGrid.h"


@implementation MLGameLayer

static MLGameLayer* gameLayer;

+(MLGameLayer*) sharedLayer{
	NSAssert(gameLayer != nil, @"MLGameLayer not available!");
	return gameLayer;
}

/*-(MLStage1*) stage1{
    CCNode* layer = [[MLGameLayer sharedLayer] getChildByTag:Stage1Tag];
    //NSAssert([layer isKindOfClass:[MLStage1 class]], @"%@: not a MLStage1!", NSStringFromSelector(_cmd));
	return (MLStage1*)layer;
}

-(MLStage2*) stage2{
    CCNode* layer = [[MLGameLayer sharedLayer] getChildByTag:Stage2Tag];
    //NSAssert([layer isKindOfClass:[MLStage2 class]], @"%@: not a MLStage2!", NSStringFromSelector(_cmd));
	return (MLStage2*)layer;
}

-(MLUserInterface*) userInterface{
	CCNode* layer = [[MLGameLayer sharedLayer] getChildByTag:UITag];
	//NSAssert([layer isKindOfClass:[MLUserInterface class]], @"%@: not a MLUserInterface!", NSStringFromSelector(_cmd));
	return (MLUserInterface*)layer;
}*/

+(id) sceneWithStage:(StageScenes)_stage{
	CCLOG(@"===========================================");
	CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
    
    return [[[self alloc] initWithStage:_stage] autorelease];
}

-(CGPoint) locationFromTouch:(UITouch*)touch{
	CGPoint touchLocation = [touch locationInView: [touch view]];
	return [[CCDirector sharedDirector] convertToGL:touchLocation];
}

-(CGPoint) locationFromTouches:(NSSet*)touches{
	return [self locationFromTouch:[touches anyObject]];
}

-(void) transitionToMenu {
    [[CCDirector sharedDirector] replaceScene:[MLLoadingScene sceneWithStage:Menu]];
}

-(void) restartStage{
    [[CCDirector sharedDirector] replaceScene:[MLLoadingScene sceneWithStage:stage]];
}

-(void) createScene{
    
    CCProgressTimer* life = [CCProgressTimer progressWithFile:@"btn_life.png"];
    life.position = CGPointMake((life.contentSize.width/2+62+63), screenSize.height-life.contentSize.height/2);
    life.type = kCCProgressTimerTypeRadialCCW;
    life.percentage = 100;
    [self addChild:life z:5 tag:LifeBtnTag];
    
    CCSprite* money = [CCSprite spriteWithFile:@"btn_money.png"];
    money.position = CGPointMake((money.contentSize.width/2+life.contentSize.width+62+63), screenSize.height-money.contentSize.height/2);
    [self addChild:money z:5 tag:MoneyBtnTag];
    
    CCSprite* tv = [CCSprite spriteWithFile:@"tv.png"];
    tv.position = CGPointMake(screenSize.width - tv.contentSize.width/2, 565);
    [self addChild:tv z:2];
    
    CCProgressTimer* tv_mask = [CCProgressTimer progressWithFile:@"tv_mask.png"];
    tv_mask.position = tv.position;
    tv_mask.type = kCCProgressTimerTypeRadialCCW;
    tv_mask.percentage = 100;
    [self addChild:tv_mask z:3 tag:TV_Mask];
    
    CCSprite* sunny = [CCSprite spriteWithFile:@"sunny.png"];
    sunny.position = tv.position;
    [self addChild:sunny z:2 tag:Sunny];
    
    CCSprite* cloudy = [CCSprite spriteWithFile:@"cloudy.png"];
    cloudy.position = tv.position;
    [self addChild:cloudy z:2 tag:Cloudy];
    //cloudy.visible = NO;
    
    CCSprite* rainy = [CCSprite spriteWithFile:@"rainy.png"];
    rainy.position = tv.position;
    [self addChild:rainy z:2 tag:Rainy];
    rainy.visible = NO;
    
    CCSprite* rainyHard = [CCSprite spriteWithFile:@"rainy_hard.png"];
    rainyHard.position = tv.position;
    [self addChild:rainyHard z:2 tag:RainyHard];
    rainyHard.visible = NO;
}

-(id) initWithStage:(StageScenes)_stage{
    
    if ((self = [super init]))
	{
		gameLayer = self;
        screenSize = [[CCDirector sharedDirector] winSize];
        lifeDowCriteria = 0;
        winTime = 0;
        
        [self createScene];
        stage = _stage;
        switch (stage) {
            case Stage1: {
                MLStage1* stage1 = [MLStage1 node];
                [self addChild:stage1 z:1 tag:Stage1Tag];
                break;
            }
            case Stage2: {
                MLStage2* stage2 = [MLStage2 node];
                [self addChild:stage2 z:1 tag:Stage2Tag];
                break;
            }
                
            case Stage3: {
                //MLStage3* stage3 = [MLStage3 node];
                //[self addChild:stage3 z:1 tag:Stage3Tag];
                break;
            }
            case Stage4: {
                //MLStage4* stage4 = [MLStage4 node];
                //[self addChild:stage4 z:1 tag:Stage4Tag];
                break;
            }
            case Stage5: {
                //MLStage5* stage5 = [MLStage5 node];
                //[self addChild:stage5 z:1 tag:Stage5Tag];
                break;
            }
            case Stage6: {
                //MLStage6* stage6 = [MLStage6 node];
                //[self addChild:stage6 z:1 tag:Stage6Tag];
                break;
            }
                
            default:
                // Always warn if an unspecified enum value was used. It's a reminder for yourself to update the switch
                // whenever you add more enum values.
                NSAssert2(nil, @"%@: unsupported stageScene %i", NSStringFromSelector(_cmd), stage);
                break;
        }
		
		MLUserInterface* uiLayer = [MLUserInterface node];
		[self addChild:uiLayer z:5 tag:UITag];
        
        // grid
        MLGrid* gridInstance = [MLGrid node];
        [self addChild:gridInstance z:4 tag:GridTag];
        
        [self schedule:@selector(tick:) interval:0.08];
	}
	
	return self;
}

-(void) tick:(ccTime)delta {
    
    winTime+=delta;
    CCNode* node = [self getChildByTag:UITag];
    MLUserInterface* uiLayer = (MLUserInterface*)node;
    node = [self getChildByTag:GridTag];
    MLGrid* gridInstance = (MLGrid*)node;
    node = [self getChildByTag:LifeBtnTag];
    CCProgressTimer* life = (CCProgressTimer*)node;
    
    int floorWater = [gridInstance getMLGridFloorKickNum];
        CCLOG(@"%i", floorWater);
    
    if((floorWater-lifeDowCriteria)>= 3000 && lifeDowCriteria == 12000)
    {
        life.percentage -= 20;
        lifeDowCriteria = 15000;
    }
    else if((floorWater-lifeDowCriteria)>= 3000 && lifeDowCriteria == 9000)
    {
        life.percentage -= 20;
        lifeDowCriteria = 12000;
    }
    else if((floorWater-lifeDowCriteria)>= 3000 && lifeDowCriteria == 6000)
    {
        life.percentage -= 20;
        lifeDowCriteria = 9000;
    }
    else if((floorWater-lifeDowCriteria)>= 3000 && lifeDowCriteria == 3000)
    {
        life.percentage -= 20;
        lifeDowCriteria = 6000;
    }
    else if((floorWater-lifeDowCriteria) >= 3000 && lifeDowCriteria == 0)
    {
        life.percentage -= 20;
        lifeDowCriteria = 3000;
    }
    
    if (winTime >= 60) {
        ccColor4B c = {0,0,0,80};
        MLWin *win = [MLWin sceneWithColor:c];
        [self addChild:win z:6];
        [self unschedule:(_cmd)];
    }
    if (life.percentage<=0) {
        ccColor4B c = {0,0,0,80};
        MLLose *lose = [MLLose sceneWithColor:c];
        [self addChild:lose z:6];
        [self unschedule:(_cmd)];
        [[SimpleAudioEngine sharedEngine]playEffect:@"fail.caf"];
    }
    
    // water leak location
    //bool leakLo[GRID_MAX_WIDTH] ={0};
    
    if(uiLayer.haveWeapon)
    {
        //CCLOG(@"touch");
        // show grid
        [gridInstance showGrid];
    }
    
    else if(uiLayer.wantToPlaceWeapon)
    {
        CCLOG(@"place");
        [uiLayer setWantToPlaceWeapon:NO];
        
        // check grid and place weapon
        
        bool isWeaponPlace = [gridInstance setGridImage:[uiLayer weapon] location:[uiLayer touchLocation]];
        [gridInstance hiddenGrid];
        [uiLayer setWeaponPlaced:isWeaponPlace];
        
    }
    else if(!uiLayer.haveWeapon)
        [gridInstance hiddenGrid];
    // set water leak location
    //leakLo = &[stage2instance getleakWaterArray];
    
    // route check & water particle
    [gridInstance startCheckRoute];
    
    // water particle
    [gridInstance setWaterEffect];
    
    [gridInstance checkSound];

    // if change bucket state
    [gridInstance changeBucketState];
     
    // Get floor kick
    [gridInstance setSoundState];
}

-(void) dealloc{
	CCLOG(@"===========================================");
    CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
	
	// The Layer will be gone now, to avoid crashes on further access it needs to be nil.
	gameLayer = nil;
    
	// don't forget to call "super dealloc"
	[super dealloc];
}

@end
